package com.teamwhole.modules.mobile.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import com.teamwhole.common.mapper.JsonMapper;
import com.teamwhole.common.model.ResultInfo;
import com.teamwhole.common.utils.StringUtils;

public class UserFilter extends org.apache.shiro.web.filter.authc.UserFilter {
	
	@Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response)
            throws IOException {
		
        // 判断当前请求是否为手机API调用
        if (isRequestFromApp((HttpServletRequest) request)) {
        	ResultInfo info = new ResultInfo();
    		info.setErrcode(-1);
    		info.setErrmsg("登陆超时.");
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out = response.getWriter();
    		out.print(JsonMapper.toJsonString(info));
    		out.close();
            return;
        }
        super.redirectToLogin(request, response);
    }

    private boolean isRequestFromApp(HttpServletRequest request) {
        String token = request.getParameter("token");
        String client = request.getParameter("client");
        if (StringUtils.isNotBlank(token) && "app".equalsIgnoreCase(client)) {
            return true;
        }
        return false;
    }
	
}
